package karaoke.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import karaoke.excepcion.DAOExcepcion;
import karaoke.modelo.Cliente;
import karaoke.modelo.Reserva;
import karaoke.modelo.Sala;
import karaoke.util.ConexionBD;

public class ReservaDAO extends BaseDAO {
	
	public Collection<Reserva> buscarPorId(int idreserva)
			throws DAOExcepcion {
		String query = "select idreserva, fecha, descripcion , idcliente from reserva where idcliente like ?";
		Collection<Reserva> lista = new ArrayList<Reserva>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, "%" + idreserva + "%");
			rs = stmt.executeQuery();
			while (rs.next()) {
				Reserva vo = new Reserva();
				vo.setIdreserva(rs.getInt("idreserva"));
				vo.setFecha(rs.getString("fecha"));
				vo.setHora(rs.getString("hora"));
				vo.setDescripcion(rs.getString("descripcion"));
				lista.add(vo);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return lista;
	}

	public Reserva insertar(Reserva vo) throws DAOExcepcion {
		String query = "insert into Reserva(fecha,hora,descripcion,idsala,idcliente) values (?,?,?,2,1)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = karaoke.util.ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1,  vo.getFecha());
			stmt.setString(2, vo.getHora());
			stmt.setString(3, vo.getDescripcion());
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			vo.setIdreserva(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}
	
	public Collection<Reserva> listar() throws DAOExcepcion {
		Collection<Reserva> c = new ArrayList<Reserva>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = karaoke.util.ConexionBD.obtenerConexion();
			String query = "select idreserva,fecha,hora,descripcion,elog  from reserva order by idreserva";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			while (rs.next()) {
				Reserva vo = new Reserva();
				vo.setIdreserva(rs.getInt("idreserva"));
				vo.setFecha(rs.getString("fecha"));
				vo.setHora(rs.getString("hora"));
				vo.setDescripcion(rs.getString("descripcion"));
				vo.setElog(rs.getBoolean("elog"));
				c.add(vo);
			}
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return c;
	}
	
	public Reserva obtener(int idReserva) throws DAOExcepcion {
		Reserva vo = new Reserva();		
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "select idreserva,fecha,descripcion,nrohoras,elog,idcliente,idsala from reserva where idreserva=?";
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setInt(1, idReserva);
			rs = stmt.executeQuery();
			if (rs.next()) {
				vo.setIdreserva(rs.getInt("idreserva"));
				String date = rs.getString("fecha");
				String fecha = date.substring(0, date.indexOf(" "));
				String hora = date.substring(date.indexOf(" ")+1, date.lastIndexOf(":"));
				vo.setFecha(fecha);
				vo.setHora(hora);
				vo.setDescripcion(rs.getString("descripcion"));
				vo.setElog((rs.getInt("elog")==1));
				vo.setNrohoras(rs.getInt("nrohoras"));
				
				ClienteDAO daoCli = new ClienteDAO();
				Cliente cliente = daoCli.obtenerPorID(rs.getInt("idcliente"));
				vo.setCliente(cliente);
				
				SalaDAO daoSala = new SalaDAO();
				Sala sala = daoSala.obtener(rs.getInt("idsala"));
				vo.setSala(sala);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

	
	public void eliminar(int idReserva) throws DAOExcepcion {
		String query = "update reserva set elog=1 WHERE idreserva=?";
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setInt(1, idReserva);
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo eliminar");
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
	}
	
	public Reserva actualizar(Reserva vo) throws DAOExcepcion {
		String query = "update reserva set fecha=?,hora =?,descripcion=? where idreserva=?";
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = karaoke.util.ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, vo.getFecha());
			stmt.setString(2, vo.getHora());
			stmt.setString(3, vo.getDescripcion());	
			stmt.setInt(4, vo.getIdreserva());

			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo actualizar");
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

	public Reserva insertarReservaCli(Reserva r) throws DAOExcepcion{
		String query = "insert into Reserva(fecha,descripcion, nrohoras, idsala, idcliente) values (?,?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = karaoke.util.ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, r.getFecha());
			stmt.setString(2, r.getDescripcion());
			stmt.setInt(3, r.getNrohoras());
			stmt.setInt(4, r.getSala().getIdSala());
			stmt.setInt(5, r.getCliente().getIdcliente());
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			r.setIdreserva(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return r;
	}
	

	public Collection<Reserva> listaReservasPorIdClienteYBusqueda(int idcliente, String idlocal, String busqueda)
			throws DAOExcepcion {
		String query = "select r.*, s.nombre, s.codigo, s.idlocal from reserva r inner join sala s on r.idsala = s.idsala and r.idcliente = ? and s.idlocal like ? where (r.elog=0 or r.elog is null) and s.nombre like ? or codigo like ?";
		Collection<Reserva> lista = new ArrayList<Reserva>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, (idcliente==0?"%":""+idcliente));
			stmt.setString(2, (idlocal.equals("")?"%":idlocal));
			stmt.setString(3, "%" + busqueda + "%");
			stmt.setString(4, "%" + busqueda + "%");
			rs = stmt.executeQuery();
			while (rs.next()) {
				Reserva vo = new Reserva();
				vo.setIdreserva(rs.getInt("idreserva"));
				vo.setFecha(rs.getString("fecha"));
				vo.setNrohoras(rs.getInt("nrohoras"));
				vo.setDescripcion(rs.getString("descripcion"));
				
				Sala s = new Sala(rs.getInt("idsala"), rs.getString("nombre"), rs.getString("codigo"));
				vo.setSala(s);
				lista.add(vo);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		System.out.println(lista.size());
		return lista;
	}
}
